package leetcode.simple.q191;

public class Main {
    public static void main(String[] args) {
        int i = hammingWeight(7);
        //System.out.println(i);

    }

    /**
     * 我的题解
     * @param n
     * @return
     */
    public static int hammingWeight(int n) {
        String s = Integer.toBinaryString(n);
        char[] chars = s.toCharArray();
        int count = 0;
        for (char c : chars) {
            if (c == '1'){
                count++;
            }
        }
        return count;
    }

    /**
     * 官方题解1
     * @param n
     * @return
     */
    public static int hammingWeight1(int n) {
        int bits = 0;
        int mask = 1;
        for (int i = 0; i < 32; i++) {
            if ((n & mask) != 0) {
                bits++;
            }
            mask <<= 1;
        }
        return bits;
    }

    /**
     * 官方题解2
     * @param n
     * @return
     */
    public static int hammingWeight2(int n) {
        int sum = 0;
        while (n != 0) {
            sum++;
            n &= (n - 1);
        }
        return sum;
    }
}
